package com.adou.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Properties;

public class sendMailMsg {
    private static final Logger logger = LoggerFactory.getLogger(sendMailMsg.class);

    public static boolean startMail(String fromMail, String user, String password, String toMail, String mailTitle, String mailContent, String smtp) {
        boolean flag = false;
        try {
            Properties props = new Properties(); //可以加载一个配置文件
            // 使用smtp：简单邮件传输协议
            props.put("mail.smtp.host", smtp);//存储发送邮件服务器的信息
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.auth", "true");//同时通过验证

            javax.mail.Session session = javax.mail.Session.getInstance(props);//根据属性新建一个邮件会话

            javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);//由邮件会话新建一个消息对象
            message.setFrom(new javax.mail.internet.InternetAddress(fromMail));//设置发件人的地址
            message.setRecipient(javax.mail.Message.RecipientType.TO, new javax.mail.internet.InternetAddress(toMail));//设置收件人,并设置其接收类型为TO
            message.setSubject(mailTitle);//设置标题
            //设置信件内容
            message.setContent(mailContent, "text/html;charset=gbk"); //发送HTML邮件，内容样式比较丰富
            message.setSentDate(new Date());//设置发信时间
            message.saveChanges();//存储邮件信息

            //发送邮件
            javax.mail.Transport transport = session.getTransport();
            transport.connect(user, password);
            transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址
            transport.close();
            flag = true;
        } catch (Exception e) {
            logger.error("邮件发送错误:" + e.toString());
        }
        return flag;
    }
}
